using System.Collections.Generic;
using NHibernate;

namespace LuceneSearch.ContactApp.Indexing
{
    public class NhIndexingInterceptor : EmptyInterceptor
    {
        private readonly EntityIndexer entityIndexer;
        private readonly List<IndexWorkItem> workItems = new List<IndexWorkItem>();

        public NhIndexingInterceptor(EntityIndexer entityIndexer)
        {
            this.entityIndexer = entityIndexer;
        }

        public override void AfterTransactionCompletion(ITransaction tx)
        {
            base.AfterTransactionCompletion(tx);

            if (tx != null && !tx.WasCommitted)
            {
                workItems.Clear();
                return;
            }

            entityIndexer.Process(workItems);
        }

        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
        {
            var baseResult = base.OnSave(entity, id, state, propertyNames, types);

            workItems.Add(new IndexWorkItem(entity, IndexWorkType.Add));

            return baseResult;
        }

        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
        {
            var baseResult = base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types);

            workItems.Add(new IndexWorkItem(entity, IndexWorkType.Update));

            return baseResult;
        }

        public override void OnDelete(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
        {
            base.OnDelete(entity, id, state, propertyNames, types);

            workItems.Add(new IndexWorkItem(entity, IndexWorkType.Delete));
        }
    }
}